/*
 * lookup functionalty unsing getaddrinfo() sytem call
 */

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <strings.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <unistd.h>
#include "lookup.h"

static const char *progname;

void
usage_help(int exit_code)
{
    fprintf(stderr, "%s -s <hostname> -p <port> [ -n ] [ -h <help> ]\n", progname);
    exit(exit_code);
}

void
error(const char *msg)
{
    printf("CUTTING\n");
    fputs(strerror(errno), stderr);
    fputc('\n', stderr);
    fputs(msg, stderr);
    fputc('\n', stderr);
    exit(1);
}

void
info(const char *msg)
{
    fputs(msg, stdout);
    fputc('\n', stdout);
}

int main(int argc, char **argv)
{
    int optch;
    char *node = NULL;
    char *port = NULL;
    int returnStatus = 0;
    int flags = 0;

    struct addrinfo hints, *res, *result;

    progname = argv[0];

    /* agrument check */
    if (argc <= 1)
	usage_help(1);

    while ((optch = getopt(argc, argv, "s:p:nh")) != -1 ) {
	switch (optch) {
	    case 's':
		node = optarg;
		break;
	    case 'p':
		port = optarg;
		break;
	    case 'n':
		flags |= NI_NUMERICHOST;
		break;
	    case 'h':
		usage_help(0);
		break;
	    default:
		usage_help(1);
		break;
	}
    }

    if (!port)
	port = PORT;

    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    /* populate addrinfo structure */
    returnStatus = getaddrinfo(node, port, &hints, &res);
    if (returnStatus == -1 ) {
	fprintf(stderr, "getaddrinfo: %s", gai_strerror(returnStatus));
	exit(1);
    }

    for (result = res; result != NULL; result = result->ai_next) {
	char hostname[BUFFERSIZE] = "";

	returnStatus = getnameinfo(result->ai_addr, result->ai_addrlen, hostname, BUFFERSIZE, NULL, 0, flags);
	if (returnStatus != 0) {
	    fprintf(stderr, "getnameinfo: %s", gai_strerror(returnStatus));
	    continue;
	}
	if (*hostname != '\0')
	    printf("hostname: %s\n", hostname);
    }

    freeaddrinfo(res);

    return 0;
}
